using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace Universe.Farm.Service
{
    class RegistryStateStorage : IStateStorage
    {
        private const string _path = "SOFTWARE\\Universe Farm\\Identity";

        public byte[] Read(string key)
        {
            string path;
            string name;
            GetPath(key, out path, out name);
            using (RegistryKey re = Registry.LocalMachine.OpenSubKey(path, false))
            {
                if (re != null)
                {
                    object raw = re.GetValue(name);
                    byte[] bytes = (byte[])raw;
                    return bytes;
                }

                return null;
            }
        }

        public void Write(string key, byte[] value)
        {
            string path;
            string name;
            GetPath(key, out path, out name);
            using (RegistryKey re = Registry.LocalMachine.CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                if (re != null)
                {
                    if (value != null)
                        re.SetValue(name, value, RegistryValueKind.Binary);
                    else
                        re.DeleteValue(name, false);
                }
            }
        }

        
        void GetPath(string key, out string path, out string name)
        {
            path = Path.Combine(_path, Path.GetDirectoryName(key));
            name = Path.GetFileName(key);
        }


    }
}
